package com.example.internet.service;

import com.example.internet.service.dto.PeopleInfoRequest;
import com.example.internet.service.dto.PeopleInfoResponse;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ContantsService {
    //服务器socket要绑定固定的端⼝
    private static final int PORT = 8888;
    public static void main(String[] args) throws IOException {
        // 创建服务端DatagramSocket，指定端⼝，可以发送及接收UDP数据报
        DatagramSocket socket = new DatagramSocket(PORT);

        // 不停接收客⼾端udp数据报
        while (true){
            System.out.println("等待接收UDP数据报...");
            // 创建 request 数据报，⽤于接收客⼾端发送的数据
            byte[] udpRequest = new byte[1024];
            // 1m=1024kb, 1kb=1024byte,
            //UDP最多64k（包含UDP⾸部8byte）
            DatagramPacket requestPacket = new DatagramPacket(udpRequest, udpRequest.length);
            // 接收 request 数据报，在接收到数据报之前会⼀直阻塞，
            socket.receive(requestPacket);
            // 获取有效的 request
            int length = BytesUtils.getValidLength(udpRequest);
            byte[] requestData = BytesUtils.subByte(udpRequest, 0, length);
            // 反序列化 request
            PeopleInfoRequest request = PeopleInfoRequest.parseFrom(requestData);
            System.out.println("接收到请求数据:");
            System.out.println(request.toString());

            // 构造 response
            PeopleInfoResponse response = PeopleInfoResponse.newBuilder().setUid("111111111").build();
            // 序列化 response
            byte[] responseData = response.toByteArray();
            // 构造 response 数据报，注意接收的客⼾端数据报包含IP和端⼝号，要设置到响应
            //的数据报中
            DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, requestPacket.getSocketAddress());
            // 发送 response 数据报
            socket.send(responsePacket);
        }
    }
}

